function hfile2 = vmp_SaveSubset(hfile, sset, nfilename)
% VMP::SaveSubset  - save a subset of maps to a new file
%
% FORMAT:       [subset] = vmp.SaveSubset(sset, newfilename)
%
% Input fields:
%
%       sset        1xN list of Maps to save
%       newfilename name for new VMP file
%
% Output fields:
%
%       subset      VMP object with sub-selection

% Version:  v0.7f
% Build:    8120122
% Date:     Dec-01 2008, 10:18 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 3 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'vmp') || ...
   ~isa(sset, 'double') || ...
    isempty(sset) || ...
    any(isinf(sset(:)') | isnan(sset(:)') | fix(sset(:)') ~= sset(:)') || ...
    any(sset(:)' < 1) || ...
   ~ischar(nfilename) || ...
    isempty(nfilename)
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
bc = bvqxfile_getcont(hfile.L);

% correctly get arguments
sset = unique(min(sset(:), bc.NrOfMaps));
if isempty(sset)
    error( ...
        'BVQXfile:BadArgument', ...
        'No maps to save remain.' ...
    );
end

% copy hfile but only wanted maps
try
    hfile2 = aft_CopyObject(hfile);
catch
    error( ...
        'BVQXfile:CopyFailed', ...
        'Error copying object for sub selection.' ...
    );
end
bc2 = bvqxfile_getcont(hfile.L);
bc2.Map = bc.Map(sset(:)');
bc2.NrOfMaps = numel(bc2.Map);
bvqxfile_setcont(hfile2.L, bc2);

% try to save
try
    aft_SaveAs(hfile2, nfilename(:)');
catch
    warning( ...
        'BVQXfile:InternalError', ...
        'Error saving maps to new file: ''%s''.', ...
        lasterr ...
    );
end

% remove object from memory
aft_ClearObject(hfile2);
